from django import forms
from django.contrib.admin import ModelAdmin
from django.contrib.auth import password_validation
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.forms import models
from django.utils.translation import ugettext_lazy as _

from app.models import FMUser
from app.models.fm_user import USER_TYPE_SALES


class FMUserCreationForm(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """
    error_messages = {
        'password_mismatch': _("The two password fields didn't match."),
    }
    password1 = forms.CharField(
        label=_("Password"),
        strip=False,
        widget=forms.PasswordInput,
        help_text=password_validation.password_validators_help_text_html(),
    )
    password2 = forms.CharField(
        label=_("Password confirmation"),
        widget=forms.PasswordInput,
        strip=False,
        help_text=_("Enter the same password as before, for verification."),
    )

    sales = models.ModelChoiceField(queryset=FMUser.objects.filter(user_type=USER_TYPE_SALES), required=False)

    class Meta:
        model = FMUser
        fields = ('username', 'realname', 'identity', 'email', 'date_of_birth',
                  # 'province', 'city', 'area', 'address', 'merchant_name', 'sales',
                  'user_type', 'sales_area', 'is_active', 'is_superuser', 'groups', 'user_permissions')

    def __init__(self, *args, **kwargs):
        super(FMUserCreationForm, self).__init__(*args, **kwargs)
        if self._meta.model.USERNAME_FIELD in self.fields:
            self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True})

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        self.instance.username = self.cleaned_data.get('username')
        password_validation.validate_password(self.cleaned_data.get('password2'), self.instance)
        return password2

    def save(self, commit=True):
        user = super(FMUserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class FMUserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField(label=u'登陆密码')
    sales = forms.ModelChoiceField(queryset=FMUser.objects.filter(user_type=USER_TYPE_SALES), label=u'对应销售',
                                   required=False)

    class Meta:
        model = FMUser
        fields = ('username', 'password', 'realname', 'identity', 'email', 'date_of_birth',
                  'province', 'city', 'area', 'address', 'merchant_name', 'sales',
                  'user_type', 'is_active', 'is_superuser', 'groups', 'user_permissions')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]


class FMUserAdmin(UserAdmin):
    form = FMUserChangeForm
    add_form = FMUserCreationForm

    list_display = ('id', 'username', 'realname', 'identity', 'email',
                    'date_of_birth', 'sales_area', 'user_type', 'is_superuser')
    list_filter = ('is_superuser', 'user_type', 'sales_area')
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (u'用户信息', {'fields': ('realname', 'identity', 'email', 'date_of_birth', 'province', 'city', 'area', 'address',
                              'merchant_name', 'sales', 'sales_area')}),
        (u'用户类型', {'fields': ('user_type', 'is_superuser', 'groups', 'user_permissions')})
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'password1', 'password2',
                       'realname', 'identity', 'email', 'date_of_birth', 'sales_area',
                       # 'province', 'city', 'area', 'address', 'merchant_name', 'sales',
                       'user_type', 'is_superuser', 'groups', 'user_permissions'),
        }),
    )
    search_fields = ('username', 'realname', 'identity', 'email')
    ordering = ('username',)
    filter_horizontal = ()


class UserAccountAdmin(ModelAdmin):
    list_display = ('id', 'user', 'balance')
